package ua.kiev.tosik.price.modules.clients.gui;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import ua.kiev.tosik.price.gui.CenterPanel;
import ua.kiev.tosik.price.gui.MainWindow;
import ua.kiev.tosik.price.gui.StatusBar;
import ua.kiev.tosik.price.gui.helper.AutoCompleteDecorator;
import ua.kiev.tosik.price.models.Clients;
import ua.kiev.tosik.price.modules.clients.RecordEditor;
import ua.kiev.tosik.price.modules.clients.conf.ModuleConfig;
import ua.kiev.tosik.price.modules.clients.database.DataQuickFindWorker;
import ua.kiev.tosik.price.modules.clients.database.files.PricesFilesDeleteAllWorker;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

public class MainToolBar implements TableModelListener {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.gui");

	private JToolBar toolBar;
	private JButton createNewButton;
	private JButton findButton;
	private JButton reloadButton;
	private JButton closeModuleButton;
	private JButton deleteAllPricesButton;
	// private JTextField quickSearch;
	private JLabel recordFoundInfo;

	private JComboBox searchComboBox;
	private DefaultComboBoxModel searchModel;
	private Vector<String> sList = new Vector<String>();

	private ActionListener createAction;
	private ActionListener reloadAction;
	private ActionListener closeModuleAction;
	private ActionListener deleteAllPricesAction;

	private ModuleConfig config;

	public MainToolBar() {
		config = ModuleConfig.getInstance();
		toolBar = new JToolBar();
		toolBar.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
		toolBar.setFloatable(false);
		initActions();
		createButtons(toolBar);
	}

	public JToolBar getToolBar() {
		return toolBar;
	}

	public void setEnable(boolean enable) {
		createNewButton.setEnabled(enable);
		findButton.setEnabled(enable);
		reloadButton.setEnabled(enable);
		closeModuleButton.setEnabled(enable);
		deleteAllPricesButton.setEnabled(enable);
		searchComboBox.setEnabled(enable);
	}

	private void initActions() {
		createAction = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				createRecord();
			}
		};
		reloadAction = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				MainPanel.getInstance().loadData();
			}
		};
		closeModuleAction = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				closeModule();
			}
		};
		deleteAllPricesAction = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				deleteAllPrices();
			}
		};
	}

	private void createButtons(JToolBar toolBar) {
		createNewButton = new JButton();
		createNewButton.addActionListener(createAction);
		findButton = new JButton();
		reloadButton = new JButton();
		reloadButton.addActionListener(reloadAction);
		closeModuleButton = new JButton();
		closeModuleButton.addActionListener(closeModuleAction);
		deleteAllPricesButton = new JButton();
		deleteAllPricesButton.addActionListener(deleteAllPricesAction);

		recordFoundInfo = new JLabel();

		toolBar.add(createNewButton);
		toolBar.add(findButton);
		toolBar.add(reloadButton);
		toolBar.addSeparator();
		toolBar.add(closeModuleButton);
		toolBar.addSeparator();
		toolBar.add(deleteAllPricesButton);
		toolBar.addSeparator();
		toolBar.add(recordFoundInfo);
		toolBar.add(Box.createHorizontalGlue());
		JPanel qsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		JLabel qsImageLabel = new JLabel(new ImageIcon(config.get("clients.toolbar.quickSearch.icon")));
		qsPanel.add(qsImageLabel);

		searchModel = new DefaultComboBoxModel();
		searchComboBox = new JComboBox();
		searchComboBox.setEditable(true);
		searchComboBox.setModel(searchModel);
		searchComboBox.setPreferredSize( new Dimension((int)searchComboBox.getPreferredSize().getWidth()+100, (int)searchComboBox.getPreferredSize().getHeight()));
		searchComboBox.addActionListener( new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if ( "comboBoxEdited".equals(e.getActionCommand()) ) {
					logger.debug("Init quick search action");
					String s = StringUtils.defaultString((String)searchComboBox.getSelectedItem());
					Clients clients = new Clients();
					clients.setName(s);
					DataQuickFindWorker findWorker = new DataQuickFindWorker(clients);
					findWorker.addPropertyChangeListener(StatusBar.getInstance());
					findWorker.execute();
					if ( !s.equals("") && s.length() >= 3 && !sList.contains((String)searchComboBox.getSelectedItem()) ) {
						searchModel.addElement(searchComboBox.getSelectedItem());
						sList.add((String)searchComboBox.getSelectedItem());
					}
				}
			}
		});

		/*
		searchComboBox.addKeyListener(new KeyListener() {
			public void keyTyped(KeyEvent e) {
				logger.debug("keyTyped: " + e.getKeyCode());
			}
			public void keyPressed(KeyEvent e) {
				logger.debug("keyPressed: " + e.getKeyCode());
			}
			public void keyReleased(KeyEvent e) {
				logger.debug("Init quick search action");
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					logger.debug("Init quick search action");
					// quickSearch.setEnabled(false);
					Clients clients = new Clients();
					clients.setName((String)searchComboBox.getSelectedItem());
					DataQuickFindWorker findWorker = new DataQuickFindWorker(clients);
					findWorker.addPropertyChangeListener(StatusBar.getInstance());
					findWorker.execute();
					searchModel.addElement(searchComboBox.getSelectedItem());
					// searchModel.
				}
			}
		}); */
		AutoCompleteDecorator.decorate(searchComboBox);
		qsPanel.add(searchComboBox);

		/*
		quickSearch = new JTextField(20);
		// quickSearch.setColumns(20);
		qsPanel.add(quickSearch);
		quickSearch.addKeyListener(new KeyListener() {
			public void keyTyped(KeyEvent e) {
			}

			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					logger.debug("Init quick search action");
					// quickSearch.setEnabled(false);
					Clients clients = new Clients();
					clients.setName(quickSearch.getText());
					DataQuickFindWorker findWorker = new DataQuickFindWorker(clients);
					findWorker.addPropertyChangeListener(StatusBar.getInstance());
					findWorker.execute();
				}
			}
		});
		*/
		setButtonLabels();
		toolBar.add(qsPanel);
	}

	public void setRecordFoundInfoText(String text) {
		recordFoundInfo.setText(text);
	}

	public void createRecord() {
		RecordEditor editor = new RecordEditor();
		editor.createRecord();
	}

	private void setButtonLabels() {
		createNewButton.setIcon(new ImageIcon(config.get("clients.toolbar.createNew.icon")));
		createNewButton.setToolTipText(config.get("clients.toolbar.createNew.text"));
		findButton.setIcon(new ImageIcon(config.get("clients.toolbar.find.icon")));
		findButton.setToolTipText(config.get("clients.toolbar.find.text"));
		reloadButton.setIcon(new ImageIcon(config.get("clients.toolbar.reload.icon")));
		reloadButton.setToolTipText(config.get("clients.toolbar.reload.text"));
		closeModuleButton.setToolTipText(config.get("clients.toolbar.close.text"));
		closeModuleButton.setIcon(new ImageIcon(config.get("clients.toolbar.close.icon")));
		deleteAllPricesButton.setIcon(new ImageIcon(config.get("clients.toolbar.deleteAll.icon")));
		deleteAllPricesButton.setToolTipText(config.get("clients.toolbar.deleteAll.text"));
	}

	private void deleteAllPrices() {
		int res = JOptionPane.NO_OPTION;
		try {
			res = JOptionPane.showConfirmDialog(MainWindow.getInstance().getFrame(), config.get("clients.files.deleteAll.text"), config.get("clients.files.table.deleteRow.text"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, new ImageIcon(config.get("clients.files.table.deleteRow.icon")));
		} catch (Exception e) {
			logger.warn(e.getLocalizedMessage());
		}
		if (res == JOptionPane.YES_OPTION) {
			PricesFilesDeleteAllWorker deleteWorker = new PricesFilesDeleteAllWorker();
			deleteWorker.addPropertyChangeListener(StatusBar.getInstance());
			deleteWorker.addPropertyChangeListener(MainPanel.getInstance());
			deleteWorker.execute();
		}
	}

	private void closeModule() {
		CenterPanel.getInstance().closeTab(MainPanel.getInstance().getModule());
	}

	@Override
	public void tableChanged(TableModelEvent e) {
		TableModel model = (TableModel) e.getSource();

		/*
		int row = e.getFirstRow();
		int column = e.getColumn();
		TableModel model = (TableModel) e.getSource();
		String columnName = model.getColumnName(column);
		Object data = model.getValueAt(row, column);
		*/
		if ( e.getType() == TableModelEvent.INSERT || e.getType() == TableModelEvent.DELETE ) {
			setRecordFoundInfoText("Found " + model.getRowCount() + " record(s)");
		}
	}

	/*private class MyListRender extends SubstanceDefaultListCellRenderer {

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
			String str = (String)value;
			if ( str != null && str.equals("") ) {
				label.setText(str);
			} else {
				label.setText(" ");
			}
			return label;
		}
	}*/

}
